import lodash from 'lodash';
import { mapGetters } from 'vuex';
import authButtons from './authButtons';
export default {
	data() {
		return {
			loading: false,
			formDialog: false,
			isChildren: false,
			queryData: { page: 1, limit: 15 },
			tableConfig: { ref: 'table', stripe: true, height: '100%' },
			formDialog: false,
			tableData: [],
			dataCount: 0,
			dataId: ''
		}
	},
	computed: {
		...mapGetters(['dictEnums', 'authButton']),
		buttons() {
			return authButtons[this.$options.name] || [];
		},
		addedButton() {
			let addedObject = this.buttons.find(n => n.field === 'added');
			return addedObject?.id;
		},
		queryButton() {
			let queryObject = this.buttons.find(n => n.field === 'query');
			return queryObject?.id;
		},
		isExistButton() {
			if (this.frameTopButton.length === 0) return false;
			return this.frameTopButton.some((n) => this.authButton.some((m) => m.id === n));
		},
		isExistQuery() {
			return this.authButton.some(n => n.id === this.queryButton);
		},
		handleButtons() {
			let handleBtns = this.buttons.filter(n => !!n.handle);
			let handleBtnMaps = lodash.keyBy(handleBtns, 'field');
			return lodash.mapValues(handleBtnMaps, item => item.id);
		},
		btnIntersections() {
			let authBtns = this.authButton.map(n => n.id);
			let handleBtns = Object.values(this.handleButtons);
			return lodash.intersection(authBtns, handleBtns);
		},
		isHasAuthButton() {
			return this.btnIntersections.length > 0;
		},
		handleWidth() {
			let columnWidth = 0;
			let handleBtns = this.buttons.filter(n => !!n.handle);
			this.btnIntersections.forEach((id, idx) => {
				let btnData = handleBtns.find(n => n.id === id);
				let labelLen = btnData?.label?.length || 0;
				columnWidth += labelLen * 15 + (idx !== 0 ? 12 : 2);
			});
			return columnWidth + 20;
		}
	},
	mounted() {
		if (!this.hasOwnProperty('activeName')) {
			this.queryTableData();
		}
	},
	methods: {
		//格式化请求参数
		async formatRequestParams() {
			if (!this.requestParams) {
				return Promise.resolve(this.queryData);
			} else {
				return Promise.resolve(this.requestParams);
			}
		},

		//获取列表数据
		async getTableData() {
			let params = await this.formatRequestParams();
			let result = await this.listFunction(params).then(res => res.data);
			if (result.code === '0') {
				this.dataCount = parseInt(result.count);
				return Promise.resolve(result.data || []);
			}
		},

		//查询列表数据
		async queryTableData() {
			this.loading = true;
			this.tableData = await this.getTableData();
			this.loading = false;
		},

		//查询数据列表
		handleQueryTableData() {
			this.queryData.page = 1;
			this.queryTableData();
		},

		handleOpenDialog(id) {
			this.dataId = !id ? '' : id;
			this.formDialog = true;
		},

		handleAddChildren(data) {
			this.dataId = data.id;
			this.formDialog = true;
			this.isChildren = true;
		},

		//点击行
		handleRowExpanded(row, column, event) {
			let treeConfig = this.treeTableConfig;
			if (column.fixed === 'right') return false;
			if (!!treeConfig && !lodash.isEmpty(treeConfig)) {
				let children = treeConfig.treeProps?.children;
				if (!!children && row[children]?.length !== 0) {
					this.$refs['table'].toggleRowExpansion(row);
				}
			}
		},

		//点击行选中
		handleRowSelected(row, column, event) {
			if (column.fixed === 'right') return false;
			if (column.type === 'selection') return false;
			this.$nextTick(() => {
				let selection = this.$refs['table'].selection;
				if (lodash.some(selection, { id: row.id })) {
					this.$refs['table'].toggleRowSelection(row, false);
				} else {
					this.$refs['table'].toggleRowSelection(row, true);
				}
			});
		},

		//格式化删除参数
		formatDeleteData(data) {
			let ids = Array.isArray(data) ? [] : '';
			if (Array.isArray(data)) {
				let tips = '';
				data.forEach(n => {
					ids.push(n.id);
					!!n.name && (tips += `【${n.name}】`);
				})
				return { ids, tips: !tips ? '' : `<font color="#f00">${tips}</font>` };
			} else {
				ids = data.id;
				return { ids, tips: !data.name ? '' : `<font color="#f00">【${data.name}】</font>` };
			}
		},

		handleDeleteData(data) {
			let params = this.formatDeleteData(data);
			let tipString = `${!params.tips ? '该' : ''}${this.pageName}${params.tips}`;
			this.$confirm(`此操作将${this.handName || '删除'}${tipString}, 是否继续?`, `${this.handName || '删除'}提示`, {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				dangerouslyUseHTMLString: true,
				type: 'warning',
				beforeClose: async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await this.deleteDataRequest(params.ids);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		async deleteDataRequest(ids) {
			let result = await this.deleteFunction(ids).then(res => res.data);
			if (result.code === '0') {
				this.$message.success(`${this.handName || '删除'}${this.pageName}成功`);
				this.updateStoreData?.();
				this.queryTableData();
			}
		}
	}
}